package com.secondshop.controllers;


import com.secondshop.models.Cart;
import com.secondshop.models.Item;
import com.secondshop.models.Order;
import com.secondshop.models.User;
import com.secondshop.services.GoodService;
import com.secondshop.services.OrderService;
import com.secondshop.services.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单接口
 */
@Controller
public class OrderController {
	private final GoodService goodService;
	private final OrderService orderService;
	private final UserService userService;
	//注入相应service
	@Autowired
	public OrderController(GoodService goodService, OrderService orderService,UserService userService) {
		this.goodService = goodService;
		this.orderService = orderService;
		this.userService=userService;
	}
	//根据orderid查询相应的订单
	@RequestMapping(value = "/user/orderInfo", method = RequestMethod.GET)
	public String getOrderInfo(ModelMap model,
			@RequestParam(value = "orderId", required = false) Integer orderId,
			HttpSession session) {
		User sessionUser = (User) session.getAttribute("user");
		if (sessionUser == null) {
			return "redirect:/";
		}
		Order orderInfo = orderService.getOrderById(orderId);
		List<Order> orders = orderService.getOtherOrderByCustomerId(
				sessionUser.getId(), orderId);
		model.addAttribute("orderInfo", orderInfo);
		model.addAttribute("orders", orders);
		return "user/orderInfo";
	}
	//获取卖家信息
	@RequestMapping(value = "/user/sellerInfo", method = RequestMethod.GET)
	public String getSellerInfo(ModelMap model,
			@RequestParam(value = "orderId", required = false) Integer orderId,
			HttpSession session) {
		User sessionUser = (User) session.getAttribute("user");
		if (sessionUser == null) {
			return "redirect:/";
		}
		Order orderInfo = orderService.getOrderById(orderId);
		List<Order> orders = orderService.getOtherOrderBySellerId(
				sessionUser.getId(), orderId);
		model.addAttribute("orderInfo", orderInfo);
		model.addAttribute("orders", orders);
		System.out.println("sellerInfo.size:" + orders.size());
		return "user/sellerInfo";
	}
	//根据orderid删除订单
	@RequestMapping(value = "/user/order/delete/{orderId}", method = RequestMethod.GET)
	public ResponseEntity deleteOrderById(@PathVariable Integer orderId) {
		Boolean success;
		success = orderService.deleteOrderById(orderId) > 0;
		return ResponseEntity.ok(success);
	}
	//根据orderid删除卖家的订单
	@RequestMapping(value = "/user/sellerOrder/delete/{orderId}&{goodId}", method = RequestMethod.GET)
	public ResponseEntity deleteSellerOrderById(@PathVariable Integer orderId,
			@PathVariable Integer goodId) {
		Boolean success;
		success = goodService.updateGoodStatusId(1, goodId) > 0;
		if (success) {
			success = orderService.deleteOrderById(orderId) > 0;
		}
		return ResponseEntity.ok(success);
	}
	//更新订单的状态
	@RequestMapping(value = "/user/order/update/status/{orderId}&{statusId}", method = RequestMethod.GET)
	public ResponseEntity updateOrderStatus(@PathVariable Integer orderId,
			@PathVariable Integer statusId) {
		Boolean success = orderService.updateStatus(statusId, orderId) > 0;
		if (success) {
			Order order = orderService.getOrderById(orderId);
			return ResponseEntity.ok(order);
		}
		return ResponseEntity.ok(success);
	}

	/**
	 * 创建订单
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/user/order/create", method = RequestMethod.POST)
	public ResponseEntity createOrder(@RequestBody Order order) {
		Boolean success = orderService.insertOrder(order) > 0;
		if (success) {
			success = goodService.updateGoodStatusId(0, order.getGoodId()) > 0;
			if (success) {
				return ResponseEntity.ok(order.getId());
			} else {
				orderService.deleteOrderById(order.getId());
				return ResponseEntity.ok(success);
			}
		}
		return ResponseEntity.ok(success);
	}
	
	//获取购物车订单信息
    @RequestMapping(value = "cart/order")
    public String checkout(HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute("user");
        // 收货地址
//        List<OsAddress> addresses = osAddressService.listAddress(user.getUserId());
//        request.setAttribute("addresses", addresses);

        // 购物车选中商品
        Cart cart = (Cart) session.getAttribute("cart");
        request.setAttribute("cart", cart);

        return "/order/showOrder";
    }
    //显示购物车订单信息
	
	@RequestMapping(value = "/order/showOrder", method = RequestMethod.GET)
    public String showCart(ModelMap mode, HttpServletRequest request) {
        String preURL = request.getHeader("Referer");
        mode.addAttribute("preURL", preURL);
        return "home/orderConfirm";
    }
	//创建购物车订单
	@RequestMapping(value = "/order/createCartOrder")
	public String createCartOrder(ModelMap mode,HttpSession session,HttpServletRequest request) {
		
		Cart cart =(Cart) session.getAttribute("cart");
		User customer=(User) session.getAttribute("user");
		List<Order> orders=new ArrayList<Order>();
		
		for(Item item:cart.getItems()) {
		Order order=new Order();
			//获取order的信息
		int goodId=item.getGood().getId();
		String goodName=item.getGood().getName();
		int sellerId =item.getGood().getUserId();
		User seller =userService.getUserById(sellerId);
		String sellerName=seller.getName();
		int customerId=customer.getId();
		String customerName=customer.getName();
		int prise=(int) item.getGood().getPrise();
		//封装order
		order.setGoodId(goodId);
		order.setGoodName(goodName);
		order.setSellerId(sellerId);
		order.setSeller(sellerName);
		order.setCustomerId(customerId);
		order.setCustomer(customerName);
		order.setMoney(prise);
		order.setStatusId(2);
		orders.add(order);
			ServletContext context=request.getServletContext();
			context.setAttribute("orders",orders);

		Boolean success = orderService.insertOrder(order) > 0;
		success = goodService.updateGoodStatusId(0, order.getGoodId()) > 0;
		}
		mode.addAttribute("orders", orders);
		

		
		
		return "home/orderConfirm";
	}

	/**
	 * 获取所有的订单
	 * @return
	 */
	@RequestMapping(value = "/user/order/allOrder", method = RequestMethod.GET)
	public ResponseEntity getAllOrders() {
		List<Order> orderList = orderService.getOrderList();
		return ResponseEntity.ok(orderList);
	}
}
